package com.github.littleantfly.dictionary.utils;

import com.github.littleantfly.dictionary.annotation.Dict;
import com.github.littleantfly.dictionary.module.DictModel;
import com.github.littleantfly.dictionary.service.DictService;
import org.springframework.util.StringUtils;

import java.util.Optional;

/**
 * @author xiezhenglong
 */
public class DictUtil {

    /**
     * 先取注解中的data值，未配置则取字段名称
     *
     * @param annotation
     * @param fieldName
     * @return
     */
    public static String getKey(Dict annotation, String fieldName) {
        String key = annotation.key();
        if (StringUtils.isEmpty(key)) {
            key = fieldName;
        }
        return key;
    }


    /**
     * 根据key获取缓存中的数据
     *
     * @param dictService
     * @param key
     * @param val
     * @return
     */
    public static Optional<DictModel> getDict(DictService dictService, String key, Object val) {
        if (val == null) {
            return Optional.empty();
        }
        return dictService.getDictData(key, val.toString());
    }

}
